<template>
  <el-container style="height: 100vh">
    <Aside/>
    <el-container>
      <el-main
          style="border-right: 1px solid transparent; border-image: linear-gradient(to bottom, #e0c3fc, #8ec5fc) 1 100%;"
      >
        <!--主页面-->
        <h1 class="title" style="color: black">Personal Information</h1>
        <div class="main-content">
          <div class="content">
            <div class="demo-fit">
              <div class="block" style="margin-left: 10%">
                <el-avatar shape="square" :size="250" :src="userAvatar"/>
              </div>
            </div>
            <br>
            <hr>
            <el-form label-width="auto" style="max-width: 600px;">
              <el-form-item label="Name:">
                <p class="el-form-content">{{ userName }}</p>
              </el-form-item>
              <el-form-item label="Email:">
                <p class="el-form-content">{{ userEmail }}</p>
              </el-form-item>
              <el-form-item label="registration date:">
                <p class="el-form-content">{{ createTime }}</p>
              </el-form-item>
            </el-form>
            <el-button
                type="primary"
                class="button"
                style="margin-left: 75%; border-radius: 20px"
                @click="drawer2 = true"
            >
              编辑个人信息
            </el-button>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>
  <!-- 抽屉内容 -->
  <el-drawer v-model="drawer2" :direction="direction" >
    <template #header>
      <h4>编辑</h4>
    </template>
    <template #default>
      <!-- default content -->
      <h1 class="texth">点击下方方框上传头像:</h1>
      <br>
      <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <br>
      <hr>
      <el-form label-width="auto">
        <el-form-item label="Old Name:">
          <p class="el-form-content">{{ userName }}</p>
        </el-form-item>
        <el-form-item label="New Name:">
          <el-input v-model="input" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import Aside from '@/components/aside.vue';
import {ref, onMounted} from 'vue';
import {getUserById, updateUser} from "@/api/user.js";
import {ElMessage, ElMessageBox, ElNotification} from 'element-plus'
import axios from "axios";

const userId = ref(null);
const user = ref(null);
const userName = ref('');
const userAvatar = ref('');
const createTime = ref('');
const userEmail = ref('');
const updateTime = ref('');
// 抽屉参数
const drawer2 = ref(false);
const direction = ref('rtl');

const input = ref('')
const code = ref('')

// 头像上传
const imageUrl = ref('');
const uploadUrl = ref('http://localhost:8081/upload');

const handleAvatarSuccess = (res, file) => {
  if (file.raw) {
    imageUrl.value = URL.createObjectURL(file.raw);
  } else {
    imageUrl.value = URL.createObjectURL(file);
  }
  ElMessage.success('上传头像成功')
};

const beforeAvatarUpload = async (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
    return false;
  }

  // 创建 FormData 并附加文件
  const formData = new FormData();
  formData.append('file', file, `${userId.value}.jpg`);

  try {
    const response = await axios.post(uploadUrl.value, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    handleAvatarSuccess(response, file);
  } catch (error) {
    console.log(error);
    ElMessage.error('上传失败');
  }

  return false; // 阻止默认上传行为
};

// 抽屉
function cancelClick() {
  drawer2.value = false;
}

const confirmClick = () => {
  ElMessageBox.confirm('确认提交修改吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        const storedUser = localStorage.getItem('user');
        if (storedUser) {
          const parsedUser = JSON.parse(storedUser);
          if (parsedUser && parsedUser.id) {
            userId.value = parsedUser.id;
            const userData = {
              name: input.value,
            };
            updateUser(userId.value, userData)
                .then(data => {
                  user.value = data;
                  code.value = user.value.code;
                  if (code.value === 200) {
                    ElNotification({
                      title: '成功',
                      message: '修改名字成功',
                      type: 'success',
                    });
                    fetchUserData(); // 获取更新后的用户信息
                  }
                })
                .catch(error => {
                  console.error('Failed to update user:', error);
                  ElNotification({
                    title: '失败',
                    message: '修改名字失败',
                    type: 'error',
                  });
                });
          }
        }
        drawer2.value = false;
      })
      .catch(() => {
        ElNotification({
          title: '取消',
          message: '操作已取消',
          type: 'warning',
        });
      });
};

const fetchUserData = () => {
  const storedUser = localStorage.getItem('user');
  if (storedUser) {
    const parsedUser = JSON.parse(storedUser);
    if (parsedUser && parsedUser.id) {
      userId.value = parsedUser.id;
      getUserById(userId.value)
          .then(data => {
            user.value = data;
            userName.value = user.value.Name;
            userAvatar.value = `http://localhost:8081/img/${user.value.Avatar}`;
            createTime.value = user.value.CreateTime;
            userEmail.value = user.value.Email;
            updateTime.value = user.value.UpdateTime;
          })
          .catch(error => {
            console.error('Failed to fetch user:', error);
          });
    }
  }
};

onMounted(() => {
  try {
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      const parsedUser = JSON.parse(storedUser);
      if (parsedUser && parsedUser.id) {
        userId.value = parsedUser.id;
        getUserById(userId.value)
            .then(data => {
              user.value = data;
              userName.value = user.value.Name;
              // console.log(userName.value)
              userAvatar.value = `http://localhost:8081/img/${user.value.Avatar}`;
              // console.log(userAvatar.value)
              createTime.value = user.value.CreateTime;
              userEmail.value = user.value.Email;
              updateTime.value = user.value.UpdateTime;
              // 打印获取到的数据
              // console.log('Fetched user data:', data);
            })
            .catch(error => {
              console.error('Failed to fetch user:', error);
            });
      }
    }
  } catch (error) {
    console.error('Failed to parse user data from localStorage:', error);
  }
});

</script>

<style>
@import url('https://fonts.googleapis.com/css2?family=Pacifico&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');

html, body {
  height: 100%;
  margin: 0;
}


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #e0c3fc, #8ec5fc);
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

//修改头像
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

// 头像
.demo-fit {
  display: flex;
  text-align: center;
  justify-content: space-between;
}

.demo-fit .block {
  flex: 1;
  display: flex;
  flex-direction: column;
  flex-grow: 0;
}

.demo-fit .title {
  margin-bottom: 10px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.el-form-item__label {
  color: black;
  font-size: 25px;
}

.el-form-content {
  font-size: 20px;
  text-decoration: underline;
  text-align: left;
  margin: 0;
}

.el-form {
  font-family: "Roboto", cursive;
}

.texth{
  font-family: "Roboto", cursive;
  color: black;
}

.el-form-item {
  color: black;
}

.main-content {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  height: 100%;
}

.text-content {
  flex: 1;
  color: black;
  font-weight: 400;
  font-style: normal;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.content {
  font-size: 30px;
  padding: 20px;
  width: 1000px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2),
  0 6px 20px rgba(0, 0, 0, 0.19);
  margin: 20px;
  font-family: Arial, sans-serif;
  background: linear-gradient(to right, #8ec5fc, #e0c3fc);
}

.title {
  font-size: 80px;
  text-align: center;
  font-family: "Pacifico", cursive;
}


// 容器样式
.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  line-height: 160px;
}

.el-header {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
  line-height: 60px;
  border-radius: 10px;
}

.el-container {
  background: linear-gradient(to right, #e0c3fc, #8ec5fc);
  height: 100%;
}
</style>
